﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using StockFinder.Indicators.Day.ClosePrice;
using StockFinder.Model;
using System.Diagnostics;
using StockFinder.Model.Constants;


namespace StockFinder.Systemtester
{
    public partial class AllTime1HighForm : Form
    {
        public AllTime1HighForm()
        {
            InitializeComponent();
        }

        private List<DailyPrice> GetSpecificPriceHistory(string filename)
        {
            var atr14 = new ExponentialMovingAverageTrueRangeClosePriceDayIndicator(14, DayIndicatorNames.CLOSE_EMATR14);
            var prices = new List<DailyPrice>();

            using (StreamReader sr = new StreamReader(filename))
            {
                string fileContents = sr.ReadToEnd();

                var lines = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                //lines = fileContents.Split(new string[] { "\n" }, StringSplitOptions.None);

                string line = string.Empty;                

                for (int j = 0; j < lines.Count(); j++)
                {
                    //ignore the first line
                    if (j > 0)
                    {
                        line = lines[j];

                        if (string.IsNullOrEmpty(line)) continue;

                        var cells = line.Split(new string[] { "," }, StringSplitOptions.None);

                        prices.Add(new DailyPrice()
                        {
                            PriceDate = DateTime.ParseExact(cells[0], "yyyyMMdd", null),
                            Open = Convert.ToDecimal(cells[1]),
                            High = Convert.ToDecimal(cells[2]),
                            Low = Convert.ToDecimal(cells[3]),
                            Close = Convert.ToDecimal(cells[4]),
                            AdjustedClose = Convert.ToDecimal(cells[4]),
                            Volume = Convert.ToInt64(cells[5])
                        });

                        //prices.Add(new DailyPrice()
                        //{
                        //    PriceDate = DateTime.ParseExact(cells[0], "yyyy-MM-dd", null),
                        //    Open = Convert.ToDecimal(cells[1]),
                        //    High = Convert.ToDecimal(cells[2]),
                        //    Low = Convert.ToDecimal(cells[3]),
                        //    Close = Convert.ToDecimal(cells[4]),
                        //    Volume = Convert.ToInt64(cells[5]),
                        //    AdjustedClose = Convert.ToDecimal(cells[6])                                    
                        //});
                    }
                }

                //prices have been filled, load indicators
                atr14.ApplyIndicator(prices);
            }

            return prices;
        }

        private List<List<DailyPrice>> GetAllPriceHistories(int count)
        {            
            const string DIRECTORY = @"C:\Data\Output\NASDAQ\";

            var files = Directory.EnumerateFiles(DIRECTORY);
            //var files = new string[]{@"C:\Users\simon\Downloads\table.csv"};

            string filename = string.Empty;

            var atr14 = new ExponentialMovingAverageTrueRangeClosePriceDayIndicator(14, DayIndicatorNames.CLOSE_EMATR14);

            List<DailyPrice> prices = new List<DailyPrice>();
            List<List<DailyPrice>> priceHistories = new List<List<DailyPrice>>();
            string[] lines = null;
            string[] cells = null;
            List<string> badFiles = new List<string>();
            if (count == -1) count = files.Count();

            for (int i = 0; i < files.Count() && i < count; i++)
            {
                Debug.WriteLine(string.Format("File {0}/{1}", i, files.Count()));

                filename = files.ElementAt(i);

                prices = new List<DailyPrice>();
                priceHistories.Add(prices);

                try
                {
                    using (StreamReader sr = new StreamReader(filename))
                    {
                        string fileContents = sr.ReadToEnd();

                        lines = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                        //lines = fileContents.Split(new string[] { "\n" }, StringSplitOptions.None);

                        string line = string.Empty;

                        for (int j = 0; j < lines.Count(); j++)
                        {
                            //ignore the first line
                            if (j > 0)
                            {
                                line = lines[j];

                                if (string.IsNullOrEmpty(line)) continue;

                                cells = line.Split(new string[] { "," }, StringSplitOptions.None);

                                prices.Add(new DailyPrice()
                                {
                                    PriceDate = DateTime.ParseExact(cells[0], "yyyyMMdd", null),
                                    Open = Convert.ToDecimal(cells[1]),
                                    High = Convert.ToDecimal(cells[2]),
                                    Low = Convert.ToDecimal(cells[3]),
                                    Close = Convert.ToDecimal(cells[4]),
                                    AdjustedClose = Convert.ToDecimal(cells[4]),
                                    Volume = Convert.ToInt64(cells[5])
                                });

                                //prices.Add(new DailyPrice()
                                //{
                                //    PriceDate = DateTime.ParseExact(cells[0], "yyyy-MM-dd", null),
                                //    Open = Convert.ToDecimal(cells[1]),
                                //    High = Convert.ToDecimal(cells[2]),
                                //    Low = Convert.ToDecimal(cells[3]),
                                //    Close = Convert.ToDecimal(cells[4]),
                                //    Volume = Convert.ToInt64(cells[5]),
                                //    AdjustedClose = Convert.ToDecimal(cells[6])                                    
                                //});
                            }
                        }

                        //prices have been filled, load indicators
                        atr14.ApplyIndicator(prices);
                    }
                }
                catch (Exception)
                {
                    badFiles.Add(filename);
                }
            }

            return priceHistories;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            const string DIRECTORY = @"C:\Data\Output\NASDAQ\";

            var files = Directory.EnumerateFiles(DIRECTORY);            
            //var files = new string[]{@"C:\Users\simon\Downloads\table.csv"};
            
            string filename = string.Empty;

            var atr14 = new ExponentialMovingAverageTrueRangeClosePriceDayIndicator(14, DayIndicatorNames.CLOSE_EMATR14);

            List<DailyPrice> prices = new List<DailyPrice>();
            string[] lines = null;
            string[] cells = null;
            List<string> badFiles = new List<string>();

            for (int i = 0; i < files.Count(); i++)
            {
                Debug.WriteLine(string.Format("File {0}/{1}", i, files.Count()));

                filename = files.ElementAt(i);

                prices.Clear();

                try
                {
                    using (StreamReader sr = new StreamReader(filename))
                    {
                        string fileContents = sr.ReadToEnd();

                        lines = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                        //lines = fileContents.Split(new string[] { "\n" }, StringSplitOptions.None);

                        string line = string.Empty;

                        for (int j = 0; j < lines.Count(); j++)
                        {
                            //ignore the first line
                            if (j > 0)
                            {
                                line = lines[j];

                                if (string.IsNullOrEmpty(line)) continue;

                                cells = line.Split(new string[] { "," }, StringSplitOptions.None);

                                prices.Add(new DailyPrice()
                                {
                                    PriceDate = DateTime.ParseExact(cells[0], "yyyyMMdd", null),
                                    Open = Convert.ToDecimal(cells[1]),
                                    High = Convert.ToDecimal(cells[2]),
                                    Low = Convert.ToDecimal(cells[3]),
                                    Close = Convert.ToDecimal(cells[4]),
                                    AdjustedClose = Convert.ToDecimal(cells[4]),
                                    Volume = Convert.ToInt64(cells[5])
                                });

                                //prices.Add(new DailyPrice()
                                //{
                                //    PriceDate = DateTime.ParseExact(cells[0], "yyyy-MM-dd", null),
                                //    Open = Convert.ToDecimal(cells[1]),
                                //    High = Convert.ToDecimal(cells[2]),
                                //    Low = Convert.ToDecimal(cells[3]),
                                //    Close = Convert.ToDecimal(cells[4]),
                                //    Volume = Convert.ToInt64(cells[5]),
                                //    AdjustedClose = Convert.ToDecimal(cells[6])                                    
                                //});
                            }
                        }

                        //prices have been filled, load indicators
                        atr14.ApplyIndicator(prices);
                    }
                }
                catch (Exception)
                {
                    badFiles.Add(filename);
                }                
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            /* find every time stock makes a new all time hight */

            DailyPrice[] history = GetSpecificPriceHistory(@"C:\SVNHome\trunk\howzat117\Common\ASPS.csv").ToArray();

            //record each price that woulod qualify as ATH
            List<DailyPrice> allTimeHighs = new List<DailyPrice>();            

            DailyPrice lastAllTime = history[0];

            allTimeHighs.Add(lastAllTime);

            for (int i = 1; i < history.Count(); i++)
            {
                var currentPrice = history[i];

                if (currentPrice.AdjustedClose > lastAllTime.AdjustedClose)
                {
                    lastAllTime = currentPrice;
                    allTimeHighs.Add(currentPrice);
                }
            }

            allTimeHighs.ForEach(h => Debug.WriteLine(string.Format("{0} | {1}", h.PriceDate, h.AdjustedClose)));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            /* find every time stock makes a new all time high but only if yesterday was not an ATH */

            DailyPrice[] history = GetSpecificPriceHistory(@"C:\Data\Output\NASDAQ\ASPS.csv").ToArray();

            //record each price that woulod qualify as ATH
            List<DailyPrice> allTimeHighs = new List<DailyPrice>();

            DailyPrice lastAllTime = history[0];

            allTimeHighs.Add(lastAllTime);

            for (int i = 1; i < history.Count(); i++)
            {
                var currentPrice = history[i];

                if (currentPrice.AdjustedClose > lastAllTime.AdjustedClose)
                {
                    lastAllTime = currentPrice;
                    allTimeHighs.Add(currentPrice);
                }
            }

            allTimeHighs.ForEach(h => Debug.WriteLine(string.Format("{0} | {1}", h.PriceDate, h.AdjustedClose)));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            /* determine entry and exit points for ATH close and ATR break */

            string filename = @"C:\Trading Data\Formatted Output\NYSE\SWI.csv";
            FileInfo fileInfo = new FileInfo(filename);

            //1 get stock price data
            DailyPrice[] history = GetSpecificPriceHistory(filename).ToArray();

            //2 loop prices
            StringBuilder result = new StringBuilder();
            int pricesCount = history.Length;
            decimal stopPrice = 0;
            DailyPrice lastAllTime = history[0];
            result.AppendLine("Date,Price,IsATH,IsStoppedOut");

            for (int i = 1; i < pricesCount; i++)
            {
                var currentPrice = history[i];

                //new high?
                if (currentPrice.AdjustedClose > lastAllTime.AdjustedClose)
                {
                    lastAllTime = currentPrice;
                    stopPrice = currentPrice.AdjustedClose - ((decimal)currentPrice.DayIndicators[DayIndicatorNames.CLOSE_EMATR14] * 10);
                    result.AppendLine(string.Format("{0},{1},{2},{3}", currentPrice.PriceDate.ToString("dd/MM/yyyy"), currentPrice.AdjustedClose, currentPrice.AdjustedClose, stopPrice));
                }
                else
                {
                    if (currentPrice.AdjustedClose < stopPrice)
                    {
                        //stopped out?
                        result.AppendLine(string.Format("{0},{1},{2},{3}", currentPrice.PriceDate.ToString("dd/MM/yyyy"), currentPrice.AdjustedClose, string.Empty, stopPrice));
                    }
                    else
                    {
                        result.AppendLine(string.Format("{0},{1},{2},{3}", currentPrice.PriceDate.ToString("dd/MM/yyyy"), currentPrice.AdjustedClose, string.Empty, stopPrice));
                    }                    
                }
            }

            File.WriteAllText(
                string.Format(@"C:\Trading Data\Results\{0}_ATH.csv", fileInfo.Name.Replace(fileInfo.Extension,string.Empty)), 
                result.ToString());
        }
    }
}
